package org.itboys.fuzion.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.fuzion.constant.FuzionConstants;
import org.itboys.fuzion.dto.FuzionMemberDto;
import org.itboys.fuzion.dto.FuzionMemberMoneyDto;
import org.itboys.fuzion.dto.FuzionMemberRedisDto;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.entity.ScoreLevel;
import org.itboys.fuzion.mysql.orm.FuziongMemberStatistics;
import org.itboys.fuzion.mysql.service.FuziongMemberStatisticsService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.redis.RedisCacheClient;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.service.WeixinConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 大乱斗的会员逻辑
 * @author weisky
 *
 * 2016年4月12日
 */
@Service
public class FuzionMemberService extends BaseService<FuzionMember, Long>{
	
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private FuziongMemberStatisticsService fuziongMemberStatisticsService;
	@Autowired
	private ScoreLevelService scoreLevelService;
	@Autowired
	private RedisCacheClient redisCacheClient;
    @Autowired
    private WeixinConfigService weixinConfigService;//publicRowService
	
	private static final Long QINGTONG_SCORE_ID = 1L;
	private static final Long BAIJIN_SCORE_ID = 2L;
	private static final Long WANGZHE_SCORE_ID = 3L;
	private static final Long ZHANSHEN_SCORE_ID = 4L;
	private static final Long TIANGANG_SCORE_ID = 5L;
	private static final Long JIAOFU_SCORE_ID = 6L;
	
	@Resource(name = "memberDS")
	private MongoDataSource ds;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}
	
	public MongoDataSource getMongoDataSource2() {
		return ds;
	}
	
	/**
	 * 保存
	 * @param member
	 * @return
	 */
	public boolean weixinInsert(FuzionMember member){
		try{
			if(StringUtils.isNotBlank(member.getPassword())){
				member.setPassword(Digests.md5(member.getPassword()));//将密码转换成MD5加密
			}
			super.save(member);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("MemberService.weixinInsert error", e);
			return false;
		}
	}
	
	/**
	 * 组装在微信的会员中心看到的信息
	 * @param memberId
	 * @return
	 */
	public FuzionMemberDto getByMemberId(Long memberId){
		FuziongMemberStatistics fms = fuziongMemberStatisticsService.getByMember(memberId);
		
		FuzionMemberDto fmd = new FuzionMemberDto();
		fmd.setScoreId(fms.getScoreId());
		if(fms != null){
			/**
			 * 青铜收益
			 */
			FuzionMemberMoneyDto qt = income(QINGTONG_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.BRONZE_MONEY);
			
			/**
			 * 白金收益
			 */
			FuzionMemberMoneyDto bj = income(BAIJIN_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.PLATINA_MONEY);
			
			/**
			 * 王者收益
			 */
			FuzionMemberMoneyDto wz = income(WANGZHE_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.KING_MONGEY);
			
			/**
			 * 战神收益
			 */
			FuzionMemberMoneyDto zs = income(ZHANSHEN_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.ZHANSHEN_MONGEY);
			
			/**
			 * 天罡收益
			 */
			FuzionMemberMoneyDto tg = income(TIANGANG_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.TIANGANG_MONGEY);
			/**
			 * 教父收益
			 */
			FuzionMemberMoneyDto jf = income(JIAOFU_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.JIAOFU_MONGEY);
			
			List<FuzionMemberMoneyDto> incomeList = Lists.newArrayListWithExpectedSize(3);
			incomeList.add(wz);
			incomeList.add(bj);
			incomeList.add(qt);
			incomeList.add(zs);
			incomeList.add(tg);
			incomeList.add(jf);
			fmd.setMoneyDto(incomeList);
			
			//if(fms.getScoreId() != 0){//有会员等级的  才能参与计算
			fmd.setEnergyBean(fms.getNowEnergyBean());//现在拥有的能量豆数量
			fmd.setHistoryAllMoney(new BigDecimal(fms.getTotalMoney()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//历史总收益 要除以100  单位变成元
			fmd.setScore(new BigDecimal(fms.getNowTotalMoney()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//当前积分  其实就是钱(剩余可提现的总金额  以分为单位  除以100  就是以元为单位)  
			fmd.setDynamicIncome(new BigDecimal(fms.getDynamicIncome()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//动态收益  直推收益
			fmd.setStaticIncome(new BigDecimal(fms.getStaticIncome()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//静态收益  每日分红（青铜收益）和开奖
			fmd.setPlayNum(fms.getPlayNum());
			//}
		}
		return fmd;
	}
	
	/**
	 * 统计当前会员推荐的数量
	 * @param recId
	 * @return
	 */
	public Long countMemberByRecId(Long recId){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
		param.put("recId", recId);
		return super.count(param);
	}
	
	/**
	 * 统计当前会员直推的数量
	 * @param recId
	 * @return
	 */
	public Long countMemberByRecId2(Long recId){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
		param.put("recId", recId);
		param.put("readed", true);
		return super.count(param);
	}
	
	/**
	 * 计算等级的各种收益
	 * @param scoreId : 积分等级ID
	 * @param sellerId : 店铺ID
	 * @param type : 积分等级类型  1：青铜  2：白金  3：王者
	 * @return
	 */
	public FuzionMemberMoneyDto income(Long scoreId, Long sellerId, int type){
		ScoreLevel sl = scoreLevelService.getById(scoreId);
		List<Long> qtMemberIdList = fuziongMemberStatisticsService.getMemberIdListByScoreId(scoreId, sellerId);//这里的ID写死了
		int qtMemberNum = qtMemberIdList.size();
		
		//这里后台控制每日分红人数
		if(sl.getPeopleNum() != null && sl.getPeopleNum() >= 0){
			qtMemberNum = sl.getPeopleNum();
		}
		
		/*if(!qtMemberIdList.isEmpty()){
			qtMemberNum = publicRowService.getNumByMemberId(qtMemberIdList);//奖金池中的青铜人数
		}*/
		FuziongMemberStatistics sellerInco = fuziongMemberStatisticsService.getSellerIncome(sellerId);//店铺收益
		
		FuzionMemberMoneyDto fmmd = new FuzionMemberMoneyDto();
		BigDecimal total = new BigDecimal(sellerInco.getNowTotalMoney()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);//总销售额
		fmmd.setPoolMoney(total.multiply(new BigDecimal(sl.getPercent())).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//奖金池 总的销售额*5%
		fmmd.setMoney(fmmd.getPoolMoney());//青铜等级收益=奖金池
		fmmd.setNum(qtMemberNum);//参与人数
		if(qtMemberNum > 0){
			fmmd.setCanMoney(fmmd.getPoolMoney().divide(new BigDecimal(qtMemberNum),2, BigDecimal.ROUND_HALF_UP));//可获收益 奖金池/青铜人数
		}
		fmmd.setType(type);//青铜级别
		return fmmd;
	}
	
	/**
	 * 将登陆的用户信息放入session会话中
	 * 将登陆的用户微信相关信息放入redis缓存中
	 * @param memberId
	 * @param request
	 * @param response
	 */
    public void setSessionMember(Long memberId, HttpServletRequest request,HttpServletResponse response){
		
    	FuzionMember member = super.getById(memberId);
		HttpSession session = request.getSession(); 
		session.setAttribute("userName", member.getNickname()); 
		session.setAttribute("headImgUrl", member.getLogo()); 
		session.setAttribute("sellerId", member.getSellerId());
		session.setAttribute("memberId", memberId);
		session.setAttribute("member", member);
		
		//设置会员的重要信息到缓存中
		getFuzionMemberRedisDto(memberId);
	}
    
    /**
     * 设置会员的重要信息到缓存中
     * @param memberId
     * @return
     */
    public FuzionMemberRedisDto getFuzionMemberRedisDto(Long memberId){
    	FuzionMemberRedisDto redis_fuzion_member = redisCacheClient.get(FuzionConstants.FUZION_MEMBER_PREFIZ_KEY + memberId, FuzionMemberRedisDto.class);
    	if(redis_fuzion_member == null){
    		FuzionMember member = super.getById(memberId);
    		FuzionMember recMember = super.getById(member.getRecId());
			WeixinConfig wc = weixinConfigService.getById(Long.parseLong(member.getWeixinId()));
			
			FuzionMemberRedisDto fmrd = new FuzionMemberRedisDto();
			if(recMember != null){
				fmrd.setRecName(recMember.getNickname());//设置推荐人名称
				fmrd.setRecHeadImgUrl(recMember.getLogo());//设置推荐人头像
			}
			fmrd.setId(memberId);
			fmrd.setOpenId(member.getOpenId());
			fmrd.setSellerId(member.getSellerId());
			fmrd.setWeixinId(member.getWeixinId());
			fmrd.setAppId(wc.getAppId());
			fmrd.setAppSecret(wc.getAppSecret());
			fmrd.setMemName(member.getNickname());
			fmrd.setRecId(member.getRecId());
			fmrd.setRecName(recMember.getNickname());
			fmrd.setRecOpenId(recMember.getOpenId());
			//放入缓存中
			redisCacheClient.set(FuzionConstants.FUZION_MEMBER_PREFIZ_KEY + memberId, fmrd, 0);
			return fmrd;
		}
    	return redis_fuzion_member;
    }

    /**
     * 获取我推荐的会员
     * @param memberId
     * @return
     */
    public List<FuzionMember> getMyNextMember(Long memberId){
    	Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
    	param.put("recId", memberId);
    	param.put("orderByKey", "-id");
    	return super.list(param);
    }

	/**
	 * 获取我直推的会员（就是已经买过商品的会员）
	 * @param memberId
	 * @return
	 */
	public List<FuzionMember> getMyBuyMember(Long memberId){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
		param.put("recId", memberId);
		param.put("readed", true);
		return super.list(param);
	}
}
